package com.applet.handler;

import com.applet.common.constant.ResultConstant;
import com.applet.common.vo.Result;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author “XuShao”
 * @date 2024/12/17 14:59
 * @description
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Result<?> ValidException(MethodArgumentNotValidException ex){
        log.error("校验失败：{}", ex.getMessage());
        BindingResult bindingResult = ex.getBindingResult();
        StringBuilder sb = new StringBuilder("校验失败:");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sb.append(fieldError.getField()).append("：").append(fieldError.getDefaultMessage()).append(", ");
        }
        String msg = sb.toString();
        return Result.fail(ResultConstant.FAIL_VERIFICATION_FAILED.getCode(), msg);
    }

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler({RuntimeException.class})
    public Result<?> exceptionHandler(RuntimeException ex){
        log.error("异常信息 => {}", ex.getMessage());
        return Result.fail(ResultConstant.FAIL_SYS_EXCEPTION.getCode(), ex.getMessage());
    }

}
